// #include "rfid_app.h"
// #include "sound_app.h"
// #include "ml307_app.h"
// #include "tp1107_app.h"
// #include "gtx31x_app.h"
#include "memroy_app.h"
// #include "safety_app.h"
#include "flash_board.h"
#include "event_board.h"
// #include "battery_app.h"
// #include "network_app.h"
#include "protocol_app.h"
#include "real_time_app.h"
#include "bluetooth_app.h"
#include "device_parameter.h"

/**
 * @brief 事件中心任务回调
 *
 */
static uint16_t EventCenterTaskCallback(uint8_t TaskId, uint16_t Events);

static uint8_t EventCenterTaskHandle = 0;
static EventCenterExternalInterfaces_t EventCenterExternalInterfaces = {0};

static uint16_t EventCenterTaskCallback(uint8_t TaskId, uint16_t Events)
{
  if (TaskId == EventCenterTaskHandle)
  {
    if (Events & SYS_EVENT_MSG)
    {
      uint8_t *pMessage = tmos_msg_receive(EventCenterTaskHandle);
      if (pMessage != NULL)
      {
        tmos_msg_deallocate(pMessage);
      }

      return (Events ^ SYS_EVENT_MSG);
    }

    if (Events & TASK_SCHEDULE)
    {
      if (EventCenterExternalInterfaces.TaskSchedule != NULL)
      {
        EventCenterExternalInterfaces.TaskSchedule();
      }

      return (Events ^ TASK_SCHEDULE);
    }

    if (Events & SCHEDULED_TASK)
    {
      if (EventCenterExternalInterfaces.ScheduledTask != NULL)
      {
        EventCenterExternalInterfaces.ScheduledTask();
      }

      return (Events ^ SCHEDULED_TASK);
    }

    if (Events & DEVICE_REBOOT_LISTER)
    {
      if (EventCenterExternalInterfaces.DeviceRebootTask != NULL)
      {
        PRINT("rebot start \r\n");
        EventCenterExternalInterfaces.DeviceRebootTask();
      }

      return (Events ^ DEVICE_REBOOT_LISTER);
    }

    if (Events & RESTORE_RESULT_LISTER)
    {
      if (EventCenterExternalInterfaces.RestoreFactoryTask != NULL)
      {
        EventCenterExternalInterfaces.RestoreFactoryTask();
      }

      return (Events ^ RESTORE_RESULT_LISTER);
    }

    if (Events & SYSTEM_FIRMWARE_UPDATE)
    {
      if (EventCenterExternalInterfaces.FirmwareUpdateTask != NULL)
      {
        EventCenterExternalInterfaces.FirmwareUpdateTask();
      }

      return (Events ^ SYSTEM_FIRMWARE_UPDATE);
    }

    if (Events & DEVICE_SELF_TEST_LISTER)
    {
      if (EventCenterExternalInterfaces.DeviceSelfTestTask != NULL)
      {
        EventCenterExternalInterfaces.DeviceSelfTestTask();
      }

      return (Events ^ DEVICE_SELF_TEST_LISTER);
    }
  }

  return 0;
}

void EventDelayMs(uint32_t Ms)
{
  Delay_Ms(Ms);
}

void EventRealTimeInitialization(void)
{
  RealTimeInitialization();
}

uint32_t EventGetCurrectTimestamp(void)
{
  return RealTimeMakeCurrentTimestamp();
}

bool EventGetRfidFunctionEnable(void)
{
  return 0;//_RFID_FUNCTION_ENABLE_;
}

bool EventGetKeyboardFunctionEnable(void)
{
  return 0;//_KEYBOARD_FUNCTION_ENABLE_;
}

bool EventGetSafetyFunctionEnable(void)
{
  return 0;//_SAFETY_VERIFYFUNCTION_ENABLE_;
}

bool EventGetNetwokFunctionEnable(void)
{
  return  0;//_NETWOK_FUNCTION_ENABLE_;
}

bool EventGetSleepFunctionEnable(void)
{
  return HAL_SLEEP;
}

bool EventGetBatteryFunctionEnableBit(void)
{
  // if (_BOARD_TYPE_ != _9905_B_BOARD_)
  //   return true;

  return false;
}

bool EventGetExternalValidationFunctionEnableBit(void)
{
  return  0;//_EXTERNAL_VALIDATION_EN_;
}

bool EventGetDayBroadcastContorlEn(void)
{
  return GetDayBroadcastContorlEn();
}

uint8_t EventGetBroadcastRemainingDays(void)
{
  return GetBroadcastRemainingDays();
}

uint8_t EventGetNormalOpenTipInterval(void)
{
  return GetNormalOpenReminderInterval();
}

uint16_t EventGetHeartbeatReportingInterval(void)
{
  return GetHeartbeatTransmissionCycle();
}

uint8_t EventUserActionTimeout(void)
{
  return GetSearchTimeout();
}

uint8_t EventRegisterTimeout(void)
{
  return (GetSearchTimeout() + REGISTER_TIME_BASED_COMPENSATION);
}

bool EventGetWhetherTheClutchIsClosed(void)
{
  // MotorLockStatus_t ClutchStaus = GetMotorActionStatus();

  // if (ClutchStaus != MOTOR_UNLOCKING)
  //   return true;

  return false;
}

bool EventGetFlaseLockAlarmEn(void)
{
  return 0;//GetFlaseLockAlarmEn();
}

bool EventGetAntiPickingAlarmEn(void)
{
  return  0;//GetAntiPickingAlarmEn();
}

bool EventGetLockedInEn(void)
{
  return  0;//GetAntiLockSignalTiggerEn();
}

bool EventGetObliqueTongueTiggerEn(void)
{
  return  0;//GetObliqueLockAlarmEn();
}

bool EventGetDoorNormalOpenEn(void)
{
  // if (GetMotorActionStatus() == MOTOR_NORMALLY_OPEN)
  //   return true;

  return false;
}

uint8_t EventGetLockedInReminderInterval(void)
{
  return GetLockedInReminderInterval();
}

uint8_t EventGetNormalOpenReminderInterval(void)
{
  return GetNormalOpenReminderInterval();
}

uint8_t EventGetFalseLockAlarmAlertInterval(void)
{
  return GetFalseLockDetcetionInterval();
}

uint8_t EventGetTheBreakInAlarmAlertInterval(void)
{
  return GetTheBreakInDetcetionInterval();
}

bool EventGetSafatyModuleBusyEn(void)
{
  // if (SafetyGetDeviceActiveEn() == true)
  //   return true;

  return false;
}

bool EventGetNetworkModuleIdleEn(void)
{
  // if (NetworkGetBusyEn() == false)
  //   return true;

  return false;
}

bool EventGetDeviceActivationStatus(void)
{
  uint8_t DeviceInitStatus = GetDeviceInitStatus() & (~FIRMWARE_UPGRADE);
  if (DeviceInitStatus == NORMAL_MODE)
    return true;

  return false;
}

void EventFlagFirmwareUpdateEnable(void)
{
  uint8_t DeviceInitStatus = GetDeviceInitStatus();

  SetDeviceInitStatus(DeviceInitStatus | FIRMWARE_UPGRADE);
  MemoryUpdateDeviceParametersNoWait();
}

bool EventGetAuthorizationExpirationEn(void)
{
  uint32_t AuthorizationEndTime = GetAuthorizationEndTime();

  if (AuthorizationEndTime != 0)
  {
    uint32_t NowTimestamp = EventGetCurrectTimestamp();

    if (NowTimestamp >= AuthorizationEndTime)
      return true;
  }

  return false;
}

uint8_t EventGetUnlockTime(void)
{
  return GetUnlockTime();
}

uint8_t EventGetSearchTimeout(void)
{
  return GetSearchTimeout();
}

uint32_t EventGetDeviceLastActionTime(void)
{
  return GetDeviceLastActionTime();
}

void EventSetDeviceLastActionTime(void)
{
  uint32_t GmtTimestamp = GetGmtTimestamp();

  SetDeviceLastActionTime(GmtTimestamp);
  MemoryUpdateDeviceParameters();
}

uint8_t EventGetDeviceStandbyTime(void)
{
  return GetBluetoothConnectionTimeout();
}

uint8_t EventGetSystemLockedTime(void)
{
  return GetSystemLockedTime() + SYSTEM_LOCKED_COMPENSATION_TIME;
}

bool EventGetTragetTypeAuthenticationErrorEn(uint8_t Type)
{
  // switch (Type)
  // {
  // case KEY_TYPE_CARD:
  // case KEY_TYPE_BLUETOOTH_VIRTUAL_CARD:
  // {
  //   if (GetRfidErrorPromptFunctionEnable() == true)
  //     return true;
  // }
  // break;

  // case KEY_TYPE_FACE:
  // case KEY_TYPE_QRCODE:
  // case KEY_TYPE_FINGER:
  // {
  //   if (GetSafetyModuleErrorPromptFunctionEnable() == true)
  //     return true;
  // }
  // break;

  // default:
  //   return true;
  // }

  return false;
}

SelfTestStartResult_t EventStartRfidSelfTest(void)
{
  // if (RfidStartDeviceSelfTestTask() == true)
  //   return SELF_TEST_START_SUCCESS;

  return SELF_TEST_START_ERROR;
}

SelfTestStartResult_t EventStartKeyboardSelfTest(void)
{
  // if (Gtx31xStartDeviceSelfTestTask() == true)
  //   return SELF_TEST_START_SUCCESS;

  return SELF_TEST_START_ERROR;
}

SelfTestStartResult_t EventStartSafetySelfTest(void)
{
  // if (SafetyStartDeviceSelfTestTask() == true)
  //   return SELF_TEST_START_SUCCESS;

  return SELF_TEST_START_ERROR;
}

SelfTestStartResult_t EventStartNetworkSelfTest(void)
{
#if _BOARD_TYPE_ != _9905_B_BOARD_
  if (NetworkInitiateSelfTestTask() == true)
    return SELF_TEST_START_SUCCESS;

  return SELF_TEST_START_ERROR;
#else
  return SELF_TEST_NO_SUPPORT;
#endif
}

ResetStartResult_t EventStartSafetyReset(void)
{
#if _BOARD_TYPE_ != _9905_B_BOARD_
  if (SafetyStartDeviceFactorySettingTask() == true)
    return RESET_START_SUCCESS;

  return RESET_START_ERROR;
#else
  return RESET_NO_SUPPORT;
#endif
}

ResetStartResult_t EventStartNetworkReset(void)
{
#if ((_BOARD_TYPE_ != _9905_B_BOARD_) && (_NETWOK_MODLE_TYPE_ == _TP1107_MODULE_))
  if (NetworkInitiateDeviceResetTask() == true)
    return RESET_START_SUCCESS;

  return RESET_START_ERROR;
#else
  return RESET_NO_SUPPORT;
#endif
}

bool EventStartRfidLocalRegister(void)
{
  return  0;//RfidStartLocalRegisterUserTask();
}

bool EventStartKeyboardLocalRegister(void)
{
  return  0;//Gtx31xStartLocalRegisterTask();
}

bool EventStartSafetyLocalRegister(void)
{
  return  0;//SafetyStartLocalRegisterUserTask();
}

bool EventStartReadCardTask(void)
{
  return  0;//RfidStartReadCardDataTask();
}

void EventStartKeyboardLocalRegisterExitListerTask(void)
{
  // Gtx31xLocalRegisterExitListerConfig();
}

void EventBatteryStartGetPercentageOfElectricity(void)
{
  // BatteryStartGetPercentageOfElectricity();
}

uint8_t EventGetVoltagePercentage(void)
{
  return 100;//BatteryGetVoltagePercentage();
}

void EventKeyboardIntoSleepMode(void)
{
  // Gtx31xIntoSleepMode();
}

void EventKeyboardIntoStandbyMode(void)
{
  // Gtx31xIntoStandbyMode();
}

void EventStartKeyInAdminPasswordMode(void)
{
  // Gtx31xStartKeyInAdminPassword();
}

void EventKeyboardIntoVerifyUserPermissionMode(void)
{
  // Gtx31xVerifyUserPermissionTask();
}

void EventPlayExitDeviceLockedState(void)
{
  // PromptExitDeviceLockedState();
}

void EventPlayDeviceLocked(void)
{
  // PromptDeviceIsInLockedState();
}

void EventPlayStartDevSelfTest(void)
{
  // PromptStartDeviceSelfTest();
}

void EventPlayExitDevSelfTest(void)
{
  // PromptExitDeviceSelfTest();
}

void EventPlayExitOnlineRegisterMode(void)
{
  // PromptExitOnlineRegisterUser();
}

void EventPlayStartUserTypedKey(void)
{
  // PromptUserKeyedKeys();
}

void EventPlayExitKeyEntry(void)
{
  // PromptExitKeyEntry();
}

void EventPlayDoorNormalOpen(void)
{
  // PromptNormalOpenTigger();
}

void EventPlayExitSafetyModuleAuthentication(void)
{
  // PromptExitSafetyModuleAuthentication();
}

void EventPlayStartSafetyModuleAuthentication(void)
{
  // PromptStartSafetyModuleAuthentication();
}

void EventPlayExitLocalRegistration(void)
{
  // PromptExitLocalRegistration();
}

void EventPlayStartLocalRegistration(void)
{
  // PromptStartLocalRegistration();
}

void EventPlayKeyInstall(void)
{
  // PromptKeyInserted();
  // PlayKeyInsertAudio();
}

void EventPlayKeyRemove(void)
{
  // PromptKeyRemove();
  // PlayKeyRemoveAudio();
}

void EventPlayAutiPickingTigger(void)
{
  // PromptAntiPickingAlarm();
}

void EventPlayAutiPickingRecovered(void)
{
  // PlayAntiPryingAlarmAduio();
  // PromptAntiPickingRecovered();
}

void EventPlayNormalOpenTigger(void)
{
  // PromptNormalOpenTigger();
}

void EventPlayNormalOpenRecovered(void)
{
  // PromptNormalOpenRecovered();
}

void EventPlayFalseLockAlarmTigger(void)
{
  // PromptFalseLockTigger();
  // PlayDoorNotCloseAudio();
}

void EventPlayFalseLockAlarmRecovered(void)
{
  // PromptFalseLockAlarmRecovered();
}

void EventPlayLockedInAlarmTigger(void)
{
  // PromptDoorLockedTigger();
}

void EventPlayLockedInAlarmRecovered(void)
{
  // PromptDoorLockedRecovered();
}

void EventPlayDevicePowerup(void)
{
  // PromptDeviceStartup();
}

void EventPlayStartup(void)
{
  // PlayStartupAudio();
}

void EventPlayDeciceAutiLock(void)
{
  // PlayAutiLockAudio();
  // PromptDoorLockedTigger();
}

void EventPlayCardReplace(void)
{
  // PlayCardReplaceAudio();
  // PromptKeyHasBeenReplaced();
}

void EventPlayAudioOfAuthenticationFailure(void)
{
  // PromptAuthenticationError();
  // PlayPermissionDeniedAudio();
}

void EventPlayAudioOfOutOfDate(void)
{
  // PlayOutOfDateAudio();
  // PromptOutOfValidityPeriod();
}

void EventPlayAudioOfDeviceLocked(void)
{
  // PromptSystemLocked();
  // PlaySystemLockAudio();
}

void EventPlayLicenseExpiredSoundEffects(void)
{
  // PlayLicenseExpiredAudio();
  // PromptAuthenticationError();
}

void EventPlayExpirationReminder(uint8_t Days)
{
  // PlayExpirationReminderAudio(Days);
}

void EventPlayDeviceNotAuthorized(void)
{
  // PromptDeviceIsInitializing();
  // PlayDeviceInTheInitializedStateAudio();
}

void EventPlaySetParameterError(void)
{
  // PlaySettingStatusAudio(false);
  // PromptSetParameterError();
}

void EventPlaySetParameterSuccess(void)
{
  // PlaySettingStatusAudio(true);
  // PromptSetParameterSuccess();
}

void EventPlayExitVerificationMode(void)
{
  // PlayExitVerificationModeAudio();
}

void EventPlayVerifyUserPermissions(void)
{
  // PromptUserKeyedKeys();
  // PlayVerifyUserPermissionsAudio();
}

void EventPlayVerifyAdminPassword(void)
{
  // PlayVerifyAdminPasswordAudio();
}

void EventPlayEquipmentBusyStatus(void)
{
  // PlayEquipmentBusyStatusAudio();
}

void EventPlayRegisterUserCount(uint8_t SuccessCount, uint8_t FailureCount)
{
  // PromptExitOnlineRegisterUser();
  // PlayRegisterUserCountAudio(SuccessCount, FailureCount);
}

void EventPlayStartOnlineRegisterUser(void)
{
  // PromptOnlineRegisterUser();
}

void EventPlayInitiateDocumentReceipt(void)
{
  // PlayInitiateDocumentReceiptAudio();
}

void EventPlayLowBattery(void)
{
  // PromptLowPower();
  // PlayLowBatteryAudio();
}

void EventPlayUserExecutelockAction(void)
{
  // PlayUserExecuteDoorLockAudio();
}

void EventPlayDoorUnlock(void)
{
  // PromptDoorUnlock();
  // PlayCurrentLockStatusAudio(true);
}

void EventPlayDoorLock(void)
{
  // PromptDoorLock();
  // PlayCurrentLockStatusAudio(false);
}

void EventPlayDoorNormallyOpen(void)
{
  // PromptNormalOpenTigger();
  // PlayNormallyOpenStatueAudio(true);
}

void EventPlaySelfTestError(uint8_t ErrorCode)
{
  // PlaySelfTestErrorAudio(ErrorCode);
  // PromptDeviceSelfTestError(ErrorCode);
}

void EventPlayExitLocalRegister(void)
{
  // PlayExitLocalRegisterAudio();
}

void EventPlayLocalRegisterStatus(bool RegisterStatus)
{
  // PlayUserRegistrationStatusAudio(RegisterStatus);
  // (RegisterStatus == true) ? PromptKeyOperationSuccess() : PromptKeyOperationError();
}

void EventPlayNetAttachStart(void)
{
  // PromptNetworkAttachmentStart();
}

void EventPlayNetAttachEnd(void)
{
  // PromptNetworkAttachmentEnd();
}

void EventPlayNetAttachStatus(uint8_t Status)
{
  // switch (Status)
  // {
  // case SEND_STATUS_DONE:
  //   PromptNetworkAttachmentSuccess();
  //   break;

  // case SEND_STATUS_HOST_NO_ACK:
  //   PromptHostConnectionLose();
  //   break;

  // default:
  //   PromptNetworkAttachmentError();
  //   break;
  // }
}

void EventPlayIntoStandbyMode(void)
{
}

void EventPlayExitStandbyMode(void)
{
}

bool EventGetNetworkQuality(void)
{
#if ((_NETWOK_FUNCTION_ENABLE_) && (_NETWOK_MODLE_TYPE_ != _RS485_MODULE_) && (_VOICE_PLAY_TYPE_ == _VOICE_PLAY_SPEAKER_))
#if _NETWOK_MODLE_TYPE_ == _ML307R_MODLE_
  uint8_t Quality = Ml307GetSignalStrength();
#elif _NETWOK_MODLE_TYPE_ == _TP1107_MODULE_
  uint8_t Quality = Tp1107GetWirelessQuality();
#endif

  PlayNetworkQualityAudio(Quality);
  return true;

#else
  return false;
#endif
}

void EventResetNetworkStatus(void)
{
  // NetworkResetWorkingStatus();
}

void EventMotorPowerUpInitialization(void)
{
  // MotorPowerUpInitialization();
}

void EventExecuteDoorLock(void)
{
  // UpdateMotorActionStatus(MOTOR_LOCK);
}

void EventExecuteDoorUnlock(void)
{
  // UpdateMotorActionStatus(MOTOR_UNLOCKING);
}

void EventExecuteDoorNormalOpen(void)
{
  // UpdateMotorActionStatus(MOTOR_NORMALLY_OPEN);
}

void EventUpdateClutchStatus(uint8_t NewStatus)
{
  // UpdateMotorActionStatus(NewStatus);
}

bool EventDetermineIfLockOffPromptIsRequired(uint8_t UnlockType)
{
  // if (UnlockType != LOG_GUEST_ROOM_CARD)
  //   return true;

  return false;
}

RegisterResult_t EventCreateNewKey(RegisterKeyInformation_t *pRegisterKeyInformationIn)
{
  uint8_t CreateReseult = 0;

  // if (pRegisterKeyInformationIn != NULL)
  // {
  //   KeyInformation_t NewKeyInformation = {0};

  //   NewKeyInformation.Count = pRegisterKeyInformationIn->Count;
  //   NewKeyInformation.KeyToken = pRegisterKeyInformationIn->KeyToken;
  //   NewKeyInformation.AuthenticationType = pRegisterKeyInformationIn->AuthenticationType;
  //   memcpy(NewKeyInformation.AuthenticationKey, pRegisterKeyInformationIn->AuthenticationKey, USER_AUTHENTICATION_KEY_LENGTH);

  //   NewKeyInformation.Date = pRegisterKeyInformationIn->Date;
  //   NewKeyInformation.EndTimestamp = pRegisterKeyInformationIn->EndTimestamp;
  //   NewKeyInformation.StartTimestamp = pRegisterKeyInformationIn->StartTimestamp;
  //   for (uint8_t i = 0; i < MAX_TIME_SLOTS; i++)
  //   {
  //     NewKeyInformation.TimePeriod[i].TimeCycle.StartHour = pRegisterKeyInformationIn->StartHour[i];
  //     NewKeyInformation.TimePeriod[i].TimeCycle.StartMinute = pRegisterKeyInformationIn->StartMinute[i];
  //     NewKeyInformation.TimePeriod[i].TimeCycle.EndHour = pRegisterKeyInformationIn->EndHour[i];
  //     NewKeyInformation.TimePeriod[i].TimeCycle.EndMinute = pRegisterKeyInformationIn->EndMinute[i];
  //   }

  //   PRINT("[info]: key type = %d. value: ", pRegisterKeyInformationIn->AuthenticationType);
  //   for (uint8_t i = 0; i < USER_AUTHENTICATION_KEY_LENGTH; i++)
  //     PRINT("%02X.", NewKeyInformation.AuthenticationKey[i]);
  //   PRINT("\r\n");

  //   CardholderCommandResult_t NewResult = NewCardholders(pRegisterKeyInformationIn->UserName, &NewKeyInformation);
  //   switch (NewResult)
  //   {
  //   case CARD_HOLDER_FULL:
  //     CreateReseult = REGISTER_USER_CARDHOLDER_IS_FULL;
  //     break;

  //   case KEY_ALREADY_EXISTS:
  //     CreateReseult = REGISTER_USER_KEY_ALREADY_EXISTS;
  //     break;

  //   case RECORD_SUCCESSFULLY:
  //     CreateReseult = REGISTER_USER_SUCCESS;
  //     break;

  //   case OVER_OF_SINGLE_USER_REGISTER_KEY:
  //     CreateReseult = REGISTER_USER_SINGLE_USER_LIMIT;
  //     break;

  //   default:
  //     CreateReseult = REGISTER_USER_ERROR;
  //     break;
  //   }
  // }

  return CreateReseult;
}

// UserAuthenticationResult_t EventVerifyAdministratorPassword(const void *pPasswordIn, uint8_t NumberOfPassword)
// {
//   char AdminPassword[NUMBER_OF_KEYBOARD_KEY] = {0};
//   const char *pVerifyKeyValue = (const char *)pPasswordIn;

//   GetSuperAdministratorPassword(AdminPassword);
//   PRINT("[info]: admin password: %s, keyin password: %s.\r\n", AdminPassword, pVerifyKeyValue);

//   if (memcmp(pVerifyKeyValue, AdminPassword, NUMBER_OF_KEYBOARD_KEY) == 0)
//     return USER_AUTHENTICATION_SUCCESS;

//   return USER_AUTHECTICATION_ERROR;
// }

// UserAuthenticationResult_t EventUserAuthentication(uint8_t KeyType, const void *pKeyValueIn, uint8_t NumberOfKey, uint8_t *pTranslatedKeyTypeOut, uint32_t *pKeyTokenOut, uint32_t *pEndTimesampOut)
// {
//   UserAuthenticationResult_t AuthenticationResult = USER_AUTHECTICATION_ERROR;

//   {
//     KeyInformation_t KeyInformation = {0};
//     CardholderCommandResult_t VerifyResult = VerifyTheValidityOfTheTypedKey(KeyType, pKeyValueIn, NumberOfKey, &KeyInformation);

//     switch (VerifyResult)
//     {
//     case AUTHENTICATION_SUCCESS:
//     {
//       AuthenticationResult = USER_AUTHENTICATION_SUCCESS;

//       if (pKeyTokenOut != NULL)
//       {
//         *pKeyTokenOut = KeyInformation.KeyToken;
//       }

//       if (pEndTimesampOut != NULL)
//       {
//         *pEndTimesampOut = KeyInformation.EndTimestamp;
//       }
//     }
//     break;

//     case NOT_IN_THE_ALLOWED_TIME:
//       AuthenticationResult = USER_OUT_OF_DATE;
//       break;

//     case CARDHOLDER_DISABLED:
//       AuthenticationResult = USER_AUTHECTICATION_ERROR;
//       break;

//     default:
//       AuthenticationResult = USER_AUTHECTICATION_ERROR;
//       break;
//     }
//   }

//   {
//     if (pTranslatedKeyTypeOut != NULL)
//     {
//       switch (KeyType)
//       {
//       case CARD_AUTHENTICATION:
//         *pTranslatedKeyTypeOut = LOG_PHYSICAL_CARD_NUMBER;
//         break;

//       case PASSWORD_AUTHENTICATION:
//         *pTranslatedKeyTypeOut = LOG_USER_KEYSCANF_PASSWORD;
//         break;

//       case QRCODE_AUTHENTICATION:
//         *pTranslatedKeyTypeOut = LOG_QR_CODE_SCANF;
//         break;

//       case FINGER_PRINTF_AUTHENTICATION:
//         *pTranslatedKeyTypeOut = LOG_FINGER_SCANF;
//         break;

//       case FACE_ID_AUTHENTICATION:
//         *pTranslatedKeyTypeOut = LOG_FACE_SCANF;
//         break;

//       case BLUETOOTH_VIRTUAL_CARD_AUTHENTICATION:
//         *pTranslatedKeyTypeOut = LOG_BLUETOOTH_VIRTUAL_CARD_NUMBER;
//         break;

//       default:
//         break;
//       }
//     }
//   }

//   return AuthenticationResult;
// }

uint16_t EventWriteUserAuthenticationLogFile(const uint8_t KeyType, const uint8_t *pKeyValueIn, uint8_t Status)
{
  return MemoryWriteUnlockLogMessage(KeyType, pKeyValueIn, Status);
}

void EventWriteDeviceStartupLogFile(void)
{
  // WriteDeviceStartupLog();
}

uint16_t EventWriteNormalOpenTiggerStatusLogFile(bool TiggerEn)
{
  // return WriteNormalOpenLog(TiggerEn);
}

bool EventGetWhetherThereAreLogsToBePushed(void)
{
  // return GetWhetherThereAreLogsToBePushed();
}

void EventDeleteAllLogFile(void)
{
  // InitialisationLogFile();
}

bool EventDetermineWhetherTheOnlineRegistrationMethodIsHostPush(uint8_t PushSource)
{
  if (PushSource == ONLINE_REGISTER_SOURCE_HOST)
    return true;

  return false;
}

void EventUploadOnlineRegisterResult(RegisterKeyInformation_t *pRegisterKeyInformationIn, RegisterResult_t RegisterResult)
{
  if (pRegisterKeyInformationIn != NULL)
  {
    ReportCardholderInformationFormat_t ReportCardholderInformationFormat = {0};

    ReportCardholderInformationFormat.Date = pRegisterKeyInformationIn->Date;
    ReportCardholderInformationFormat.Count = pRegisterKeyInformationIn->Count;
    ReportCardholderInformationFormat.KeyType = pRegisterKeyInformationIn->AuthenticationType;
    ReportCardholderInformationFormat.KeyToken = pRegisterKeyInformationIn->KeyToken;
    ReportCardholderInformationFormat.StartTimestamp = pRegisterKeyInformationIn->StartTimestamp;
    ReportCardholderInformationFormat.EndTimestamp = pRegisterKeyInformationIn->EndTimestamp;
    memcpy(ReportCardholderInformationFormat.UserName, pRegisterKeyInformationIn->UserName, USER_NAME_LENGTH);
    memcpy(ReportCardholderInformationFormat.KeyValue, pRegisterKeyInformationIn->AuthenticationKey, USER_AUTHENTICATION_KEY_LENGTH);

    for (uint8_t i = 0; i < MAX_TIME_SLOTS; i++)
    {
      ReportCardholderInformationFormat.TimePeriod[i].StartMinute = pRegisterKeyInformationIn->StartMinute[i];
      ReportCardholderInformationFormat.TimePeriod[i].StartHour = pRegisterKeyInformationIn->StartHour[i];
      ReportCardholderInformationFormat.TimePeriod[i].EndMinute = pRegisterKeyInformationIn->EndMinute[i];
      ReportCardholderInformationFormat.TimePeriod[i].EndHour = pRegisterKeyInformationIn->EndHour[i];
    }

    uint8_t OnlineRegisterResult = 0;
    switch (RegisterResult)
    {
    case REGISTER_USER_SUCCESS:
      OnlineRegisterResult = MESSAGE_PRASE_SUCCESS;
      break;

    case REGISTER_USER_DEVICE_BUSY:
      OnlineRegisterResult = TARGET_DEVICE_BUSY;
      break;

    case REGISTER_SAFETY_USER_IS_FULL:
      OnlineRegisterResult = SAFETY_USER_IS_FULL;
      break;

    case REGISTER_USER_SINGLE_USER_LIMIT:
      OnlineRegisterResult = OVER_OF_SINGLE_USER_REGISTER;
      break;

    case REGISTER_USER_TIMEOUT:
      OnlineRegisterResult = OPERATION_TIMED_OUT_PLEASE_RETRY;
      break;

    case REGISTER_USER_KEY_ALREADY_EXISTS:
      OnlineRegisterResult = CARDHOLDER_ALREADY_EXISTS;
      break;

    case REGISTER_USER_CARDHOLDER_IS_FULL:
      OnlineRegisterResult = EXCEED_USER_LIMIT;
      break;

    case REGISTER_USER_FILE_ERROR:
      OnlineRegisterResult = FILE_CHECK_FAILED;
      break;

    default:
      OnlineRegisterResult = OPERATION_FAILURE;
      break;
    }

    ProtocolUploadOnlineRegisterResult(&ReportCardholderInformationFormat, OnlineRegisterResult);
  }
}

void EventRealTimePushOfUnlockEvent(uint16_t LogId, uint8_t KeyType, const uint8_t *pKeyValueIn)
{
  if (pKeyValueIn != NULL)
  {
    // ProtocolUploadLogEventToHost(LogId, KeyType, CARDHOLDER_AUTHENTICATION_SUCCESS, pKeyValueIn);
  }
}

void EventRealTimePushOfAlarmEvent(uint16_t LogId, uint8_t AlarmEvent, uint8_t TiggerEn)
{
  ProtocolUploadLogEventToHost(LogId, AlarmEvent, TiggerEn, NULL);
}

void EventUpdateBluetoothRadio(void)
{
  BluetoothUpdateRadioPackage();
}

void EventDeleteAllCardholder(void)
{
  // InitialiseCardholderDirectory();
}

void EventRestoreDefaultUserParameters(void)
{
  RestoreDefaultUserParameters();
  MemoryUpdateDeviceParameters();
}

bool EventInitialisingDeviceParameters(void)
{
  return MemoryInitialisingdeviceparameters();
}

bool EventStartExternalValidation(void)
{
  return 0;//SafetyStartUserAuthenticationTask();
}

void EventSafetyModuleIntoPowerDown(void)
{
  // SafetyStartForcedToGotoSleepTask();
}

void EventSafetyModuleDeleteSpecificKey(const uint8_t *pKeyValueIn)
{
  if (pKeyValueIn != NULL)
  {
    uint16_t UserId = 0;

    UserId = pKeyValueIn[0] << 8;
    UserId |= pKeyValueIn[1];
    // SafetyStartDeletingSpecificUsersTask(UserId);
  }
}

void EventSendHeartbeatToServer(void)
{
  ProtocolSendHeartbeatToHost();
}

void EventActivePushHeartbeatToHost(void)
{
  ProtocolActivePushHeartbeatToHost();
}

void EventForceEndMessageSend(void)
{
  ProtocolResetMessageQueue();
}

void EventDisableRfidFunction(void)
{
  // RfidDisableCardDecetionFunction();
}

void EventEnableRfidFunction(void)
{
  // RfidEnableCardDecetionFunction();
}

void EventDisableKeyboardFunction(void)
{
  // Gtx31xDiableKeyboardFunction(0);
}

void EventEnableKeyboardFunction(void)
{
  // Gtx31xEnableKeyboardFunction();
}

void EventRfidExitCurrectMode(void)
{
  // RfidExitCurrectTask();
}

bool EventCheckIfTheIndicatorLightIsOn(void)
{
  return 0;//CheckIfTheIndicatorLightIsOn();
}

void EventActionBeforeSleep(void)
{
  // NetworkIntoPowerDown();
  // StopAllLightAlerts();
}

void EventSoftwareReset(void)
{
  PRINT("rebot begin\r\n");
   NVIC_SystemReset();
  // SYS_ResetExecute();
}

void EventDisableAllInterrupt(void)
{
  // DisableAllSensorInSoucre();
}

void EventEnableAllInterrupt(void)
{
  // EnableAllSensorInSoucre();
}

uint8_t *EventMalloc(uint16_t MallocSize)
{
  return tmos_msg_allocate(MallocSize);
}

void EventFree(void *ptr)
{
  tmos_msg_deallocate((uint8_t *)ptr);
}

void EventStopTaskSchedule(void)
{
  tmos_stop_task(EventCenterTaskHandle, TASK_SCHEDULE);
}

void EventStartTaskSchedule(void)
{
  tmos_stop_task(EventCenterTaskHandle, TASK_SCHEDULE);
  tmos_set_event(EventCenterTaskHandle, TASK_SCHEDULE);
}

void EventStopScheduleTask(void)
{
  tmos_stop_task(EventCenterTaskHandle, SCHEDULED_TASK);
}

void EventDelayedStartScheduleTask(uint32_t DelayTime)
{
  tmos_stop_task(EventCenterTaskHandle, SCHEDULED_TASK);
  tmos_start_task(EventCenterTaskHandle, SCHEDULED_TASK, MS1_TO_SYSTEM_TIME(DelayTime));
}

void EventStartScheduleTaskNoWait(void)
{
  tmos_stop_task(EventCenterTaskHandle, SCHEDULED_TASK);
  tmos_set_event(EventCenterTaskHandle, SCHEDULED_TASK);
}

void EventStopDeviceRebootTask(void)
{
  tmos_stop_task(EventCenterTaskHandle, DEVICE_REBOOT_LISTER);
}

void EventDelayedStartDeviceRebootTask(uint32_t DelayTime)
{
  tmos_stop_task(EventCenterTaskHandle, DEVICE_REBOOT_LISTER);
  tmos_start_task(EventCenterTaskHandle, DEVICE_REBOOT_LISTER, MS1_TO_SYSTEM_TIME(DelayTime));
}

void EventStopRestoreFactoryTask(void)
{
  tmos_stop_task(EventCenterTaskHandle, RESTORE_RESULT_LISTER);
}

void EventDelayedStarRestoreFactoryTask(uint32_t DelayTime)
{
  tmos_stop_task(EventCenterTaskHandle, RESTORE_RESULT_LISTER);
  tmos_start_task(EventCenterTaskHandle, RESTORE_RESULT_LISTER, MS1_TO_SYSTEM_TIME(DelayTime));
}

void EventStartRestoreFactoryTaskNoWait(void)
{
  tmos_stop_task(EventCenterTaskHandle, RESTORE_RESULT_LISTER);
  tmos_set_event(EventCenterTaskHandle, RESTORE_RESULT_LISTER);
}

void EventStopIntoFirmwareUpdateTask(void)
{
  tmos_stop_task(EventCenterTaskHandle, SYSTEM_FIRMWARE_UPDATE);
}

void EventDelayedStartIntoFirmwareUpdateTask(uint32_t DelayTime)
{
  tmos_stop_task(EventCenterTaskHandle, SYSTEM_FIRMWARE_UPDATE);
  tmos_start_task(EventCenterTaskHandle, SYSTEM_FIRMWARE_UPDATE, MS1_TO_SYSTEM_TIME(DelayTime));
}

void EventStartIntoFirmwareUpdateTaskNoWait(void)
{
  tmos_stop_task(EventCenterTaskHandle, SYSTEM_FIRMWARE_UPDATE);
  tmos_set_event(EventCenterTaskHandle, SYSTEM_FIRMWARE_UPDATE);
}

void EventStopDeviceSelfTestTask(void)
{
  tmos_stop_task(EventCenterTaskHandle, DEVICE_SELF_TEST_LISTER);
}

void EventDelayedStartDeviceSelfTestTask(uint32_t DelayTime)
{
  tmos_stop_task(EventCenterTaskHandle, DEVICE_SELF_TEST_LISTER);
  tmos_start_task(EventCenterTaskHandle, DEVICE_SELF_TEST_LISTER, MS1_TO_SYSTEM_TIME(DelayTime));
}

void EventStartDeviceSelfTestTaskNoWait(void)
{
  tmos_stop_task(EventCenterTaskHandle, DEVICE_SELF_TEST_LISTER);
  tmos_set_event(EventCenterTaskHandle, DEVICE_SELF_TEST_LISTER);
}

bool ThrowEventToEventCenter(uint8_t Event, const void *pDataIn, uint8_t DataSize)
{
  if (DataSize <= EVENT_CARRYING_DATA_LENGTH)
  {
    if (DataSize > 0)
    {
      if (pDataIn == NULL)
        return false;
    }

    EventPacket_t *pEventMessage = (EventPacket_t *)tmos_msg_allocate(sizeof(EventPacket_t));
    if (pEventMessage != NULL)
    {
      pEventMessage->Type = Event;
      memcpy(pEventMessage->DataPacket, pDataIn, DataSize);
      tmos_msg_send(EventCenterTaskHandle, (uint8_t *)pEventMessage);

      return true;
    }
  }

  return false;
}

void EventCenterBoardInitialisation(EventCenterExternalInterfaces_t *pExternalInterfaces)
{
  EventCenterExternalInterfaces.TaskSchedule = pExternalInterfaces->TaskSchedule;
  EventCenterExternalInterfaces.ScheduledTask = pExternalInterfaces->ScheduledTask;
  EventCenterExternalInterfaces.DeviceRebootTask = pExternalInterfaces->DeviceRebootTask;
  EventCenterExternalInterfaces.RestoreFactoryTask = pExternalInterfaces->RestoreFactoryTask;
  EventCenterExternalInterfaces.FirmwareUpdateTask = pExternalInterfaces->FirmwareUpdateTask;
  EventCenterExternalInterfaces.DeviceSelfTestTask = pExternalInterfaces->DeviceSelfTestTask;
  EventCenterTaskHandle = TMOS_ProcessEventRegister(EventCenterTaskCallback);
}
